class List{
    page = 1;
    pageNum = 4;
    onOff = false;
    constructor(){
        this.getData(this.page);
        this.changeCartNum(); 
        document.onscroll = this.scrollFn.bind(this);
    }
    // 获取数据
    async getData(curPage){
        // layer.msg('加载中...')
        //分割数组
        let start = (curPage - 1) * this.pageNum;
        // console.log(start);
        let end = curPage * this.pageNum;
        // console.log(end);
        let size = 100;
        // 发送ajax请求，获取数据
        let {data, status} = await axios.get('http://localhost:8888/goods/list?pagesize=' +size);
        // console.log(data, status);
        // 设置延时器
        setTimeout(() => {
            let res = data.list.slice(start,end);
            // console.log(res);
            if(!res.length){
                // layer.msg('没有了...')
            }
            let html = '';
            res.forEach(goods => {
                html+=`
                    <li class="yui3-u-1-5">
                    <div class="p-img">
                        <a href="./item.html?goods_id=${goods.goods_id}"><img src="${goods.img_big_logo}"></a>
                    </div>
                    <div class="attr"><em>${goods.title}</em></div>
                    <div class="price"><strong><em>¥</em><i>${goods.current_price}</i></strong><s>￥${goods.price}</s></div>
                    <div class="sold"><span>已售<i>${goods.sale_type}</i></span><img src="./uploads/state_07.png" alt=""><span>剩余<i>${goods.goods_number}</i></span></div>
                    <div class="operate">
                        <a href="#none" class="add" onclick='List.addCart(${goods.goods_id})'>立即抢购</a>
                    </div>
                </li>`
            })
            this.$('.goods-list .yui3-g').innerHTML += html;
            this.scrollFn();
        })
    } 

    // 懒加载
    scrollFn(){
        // 获取可视区域的高度
        let boxH = document.documentElement.clientHeight;
        // console.log(boxH);
         // 获取滚动条的高度
        let top = document.documentElement.scrollTop;
        // console.log(top);
        // 获取内容区域的高度
        // console.log(this.$('.goods-list'));
        // console.log(this.$('.goods-list .yui3-g').lastElementChild);
        let content = this.$('.goods-list .yui3-g').lastElementChild.offsetTop;
        // console.log(content);
        // 设置一个变量控制懒加载的时间间隔
        // 判断什么时候加载
        if(boxH + top > content){
            // console.log(22222);
            if(this.lock) return;
            this.lock = true;
            this.getData(++this.page);
            // console.log(3333);
            setTimeout(() => {
                this.lock = false;
            },500)
        }
    }
    static addCart(goods_id){
         // 判断是否登录
        // 获取token的值
        let token = localStorage.getItem('token');

        // 若token值为空，则跳转到登陆页面登陆，不为空则跳转到购物车页面
        if(!token)  location.assign('./login.html?returnUrl=./list.html');
        layer.confirm('是否加入购物车？', {
            btn: ['是', '再看看'] //按钮
        }, function (index) {
            layer.close(index)
            List.toAddCart(goods_id);
            // this.changeCartNum(); 
        })
    }
    // 添加购物车
    static toAddCart(goods_id){

            let userId = localStorage.getItem('use_id');
            console.log(userId, goods_id);

            // 拼接参数
            let param = `id=${userId}&goodsId=${goods_id}`;

            // 设置参数格式
            axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

            // 设置token值
            axios.defaults.headers.common['Authorization'] = localStorage.getItem('token');

            // 发送ajax请求
            axios.post('http://localhost:8888/cart/add',param).then(({data, status}) => {
                // console.log(data,status);
                // 判断是否请求成功
                if(status != 200) return ;
                // 接口没有请求成功则返回到登录页面重新登录
                if(data.code == 0) location.href = './login.html';
            }) 
        
    }

    // 实时改变购物车的数量
    async changeCartNum(){
        console.log(1111);
        //获取用户id
        let userId = localStorage.getItem('use_id');
        // console.log(userId);

        //携带token
        axios.defaults.headers.common['Authorization'] = localStorage.getItem('token');

        // 发送ajax请求
        let { status, data } = await axios.get('http://localhost:8888/cart/list?id=' + userId);

        if (status == 200 && data.code == 1) {
        // console.log(status, data);
        let sum = 0;
        data.cart.forEach(ele =>{
           // console.log(ele.cart_number);
           sum += ele.cart_number;
        //    console.log(sum);
        })
        // this.$('.allgoods .num').innerHTML = sum;
        this.$('.sui-btn .shopnum').innerHTML = sum;
       }
    }

    // 获取节点
    $(ele){
        let res = document.querySelectorAll(ele);
        return res.length == 1 ? res[0] : res;
    }
}
new List;